#pragma once
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <netinet/in.h>
#include "log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <functional>
#include <unordered_map>

typedef std::function<std::string(const std::string &)> func_t;

Log lg;

const uint16_t defaultport = 8080;
const std::string defaultip = "0.0.0.0";

const int size = 1024;

class UdpServe
{
public:
  UdpServe(uint16_t port = defaultport, std::string ip = defaultip) : _socketfd(0), _port(port), _ip(ip), _isRuning(false)
  {
  }

  void Init()
  {
    // 1. 创建 socket
    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd < 0)
    {
      lg(Fatal, "socketfd create failed, error: %s", strerror(errno));
      exit(1);
    }
    lg(Info, "socket create success, socketfd: %d, errmsg: %s", socketfd, strerror(errno));
    _socketfd = socketfd;

    // 2. 绑定(bind) socket

    // 先创建一个本地的结构体
    struct sockaddr_in local;
    bzero(&local, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(_port);
    local.sin_addr.s_addr = inet_addr(_ip.c_str());

    // 绑定端口号服务器
    int bret = bind(_socketfd, (const sockaddr *)&local, sizeof(local));
    if (bret < 0)
    {
      lg(Fatal, "bind port&ip failed, error: %s", strerror(errno));
      exit(1);
    }
    lg(Info, "bind port&ip success, bind: %d, errmsg: %s", bret, strerror(errno));
  }

  void checkUser(const struct sockaddr_in &client, const uint16_t &clientport, const std::string &clientip)
  {
    auto find = _online.find(clientip);
    if (find == _online.end())
    {
      _online.insert({clientip, client});
      std::cout << "[" << clientip << " " << clientport << "]" << "add to online, welcome" << std::endl;
    }
  }

  void broadcast(const std::string &info, const uint16_t &clientport, const std::string &clientip)
  {
    std::string message = "[";
    message += clientip;
    message += ": ";
    message += std::to_string(clientport);
    message += "]";
    message += "#";

    message += info;

    for (auto &user : _online)
    {
      sendto(_socketfd, message.c_str(), message.size(), 0, (struct sockaddr *)(&user.second), sizeof(user.second));
    }
  }

  void Run()
  {
    // std::cout << "run start" << std::endl;
    _isRuning = true;
    char buffer[size];
    while (_isRuning)
    {
      memset(buffer, 0, sizeof(buffer));
      // 接收数据
      struct sockaddr_in client;
      socklen_t len = sizeof(client);

      ssize_t rcv = recvfrom(_socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client, &len);

      if (rcv < 0)
      {
        lg(Warning, "recvfrom failed, err: %s", strerror(errno));
        continue;
      }
      // lg(Info, "recvfrom success, rcv: %d, errmdg: %s", rcv, strerror(errno));
      buffer[rcv] = 0;

      uint16_t clientport = ntohs(client.sin_port);
      std::string clientip = inet_ntoa(client.sin_addr);
      checkUser(client, clientport, clientip);

      std::string info = buffer;
      broadcast(info, clientport, clientip);

      // // 处理数据
      // std::string sendmsg = func(buffer);
      // // std::string sendmsg = "Client say# ";
      // // sendmsg += buffer;
      // // std::cout << sendmsg << std::endl;
      // // 发送数据
      // int sret = sendto(_socketfd, sendmsg.c_str(), sendmsg.size(), 0, (const sockaddr *)&info, len);
      // if (sret < 0)
      // {
      //   lg(Warning, "sendto message failed, err: %d, errmsg: %s", errno, strerror(errno));
      //   continue;
      // }
      // lg(Info, "sendto message success, sret: %d, errmsg: %s", sret, strerror(errno));
    }
  }

  ~UdpServe()
  {
    close(_socketfd);
  }

private:
  int _socketfd;   // socket 文件描述符
  uint16_t _port;  // 端口号
  std::string _ip; // ip地址// 要接收任意地址的ip直接0.0.0.0
  bool _isRuning;

  unordered_map<std::string, struct sockaddr_in> _online;
};